package com.sec.etech.employeesync.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.employeesync.config.ConfigManager;
import com.sec.etech.employeesync.entity.OrgEmployee;
import com.sec.etech.sys.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openbpm.org.api.model.IUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 齐马的作品
 * @version : 1.0
 * @date : 2024/9/10 下午1:21
 * @description:
 */

@Component
@Slf4j
public class EmployeeConverter {
    @Autowired
    private ConfigManager configManager;

    @Autowired
    private EmployeeFilterHandler employeeFilterHandler;

    public List<OrgEmployee> getNewEmployeeList(JSONArray etResultArray, IUser iUser) {
        etResultArray.parallelStream()
                .map(obj -> (JSONObject) obj)
                .forEach(obj -> {
                    ContextUtil.setCurrentUser(iUser);
                    preCreateConfig(obj);
                });

        return etResultArray.parallelStream()
                .map(obj -> (JSONObject) obj)
                .filter(employeeFilterHandler::isEmployeeFilter)
                .map(this::convertToOrgEmployee)
                .collect(Collectors.toList());
    }

    private OrgEmployee convertToOrgEmployee(JSONObject employeeData) {
        OrgEmployee employee = new OrgEmployee();

        // 工号
        employee.setAccount(StringUtils.trimToNull(employeeData.getString("PERNR")));

        // 姓名
        String sname = StringUtils.trimToNull(employeeData.getString("SNAME"));
        if (StringUtils.isNotBlank(sname)) {
            employee.setFullname(sname.replaceAll("\\s+", ""));
        }

        // 性别
        String gesch = StringUtils.trimToNull(employeeData.getString("GESCH"));
        if (StringUtils.isNotBlank(gesch)) {
            employee.setSex("1".equals(gesch) ? 1 : 0);
        }

        // 民族
        String zminzu = StringUtils.trimToNull(employeeData.getString("ZMINZU"));
        if (StringUtils.isNotBlank(zminzu)) {
            employee.setEthnicityId(configManager.getConfigId("ethnicity", zminzu));
        }

        // 出生日期
        employee.setBirthDate(parseDate(StringUtils.trimToNull(employeeData.getString("GBDAT"))));

        // 年龄
        employee.setAge(employeeData.getIntValue("AGE"));

        // 国籍
        String nationalityCode = StringUtils.trimToNull(employeeData.getString("NATIO"));
        if (StringUtils.isNotBlank(nationalityCode)) {
            employee.setNationalityId(configManager.getConfigId("nationality", nationalityCode));
        }

        // 籍贯
        String zhrhometown = StringUtils.trimToNull(employeeData.getString("ZHRHOMETOWN"));
        if (StringUtils.isNotBlank(zhrhometown)) {
            employee.setNativePlaceId(configManager.getConfigId("nativePlace", zhrhometown));
        }

        // 手机号
//        employee.setMobile(StringUtils.trimToNull(employeeData.getString("USRID")));

        // 政治面貌
        String pcode = StringUtils.trimToNull(employeeData.getString("PCODE"));
        if (StringUtils.isNotBlank(pcode)) {
            employee.setPoliticsId(configManager.getConfigId("politics", pcode));
        }

        // 产业集团（二级）
//        String orgtxGroup = StringUtils.trimToNull(employeeData.getString("ORGTX_GROUP"));
//        if (StringUtils.isNotBlank(orgtxGroup)) {
//            employee.setIndustrialGroupId(configManager.getConfigId("industrialGroup", orgtxGroup));
//        }

        // 公司（三级）
        String bukrs = StringUtils.trimToNull(employeeData.getString("BUKRS"));
        if (StringUtils.isNotBlank(bukrs)) {
            employee.setCompanyId(configManager.getConfigId("company", bukrs));
        }

        // 所属公司
        String orgtxComp = StringUtils.trimToNull(employeeData.getString("ORGTX_COMP"));
        employee.setPersonnelDepartment(orgtxComp);

        // 一级部门
        String orgtx1 = StringUtils.trimToNull(employeeData.getString("ORGTX1"));
        if (StringUtils.isNotBlank(orgtx1)) {
            employee.setPrimaryDepartmentId(configManager.getConfigId("department", orgtx1));
        }

        // 二级部门
        String orgtx2 = StringUtils.trimToNull(employeeData.getString("ORGTX2"));
        if (StringUtils.isNotBlank(orgtx2)) {
            employee.setSecondaryDepartmentId(configManager.getConfigId("department", orgtx2));
        }

        // 三级部门
        String orgtx3 = StringUtils.trimToNull(employeeData.getString("ORGTX3"));
        if (StringUtils.isNotBlank(orgtx3)) {
            employee.setTertiaryDepartmentId(configManager.getConfigId("department", orgtx3));
        }

        // 职位描述
        employee.setJobName(StringUtils.trimToNull(employeeData.getString("PLSTX")));

        // 一级岗位目录
        String zyjgwml = StringUtils.trimToNull(employeeData.getString("ZYJGWML"));
        // 一级岗位目录文本
        String zyjgwwb = StringUtils.trimToNull(employeeData.getString("ZYJGWWB"));
        if (StringUtils.isNotBlank(zyjgwwb)) {
            employee.setPrimaryLevelJobId(configManager.getConfigId("primaryLevelJob", zyjgwwb));
        }

        // 二级岗位目录
        String zejgwml = StringUtils.trimToNull(employeeData.getString("ZEJGWML"));
        // 二级岗位目录文本
        String zejgwwb = StringUtils.trimToNull(employeeData.getString("ZEJGWWB"));
        if (StringUtils.isNotBlank(zejgwml) && StringUtils.isNotBlank(zejgwwb)) {
            employee.setSecondaryLevelJobId(configManager.getConfigId("secondaryLevelJob", zejgwml, zejgwwb));
        }

        // 三级岗位目录
        String zsjgwml = StringUtils.trimToNull(employeeData.getString("ZSJGWML"));
        // 三级岗位目录文本
        String zsjgwwb = StringUtils.trimToNull(employeeData.getString("ZSJGWWB"));
        if (StringUtils.isNotBlank(zsjgwml) && StringUtils.isNotBlank(zsjgwwb)) {
            employee.setTertiaryLevelJobId(configManager.getConfigId("tertiaryLevelJob", zsjgwml, zsjgwwb));
        }

        // 员工组
        String persg = StringUtils.trimToNull(employeeData.getString("PERSG"));
        if (StringUtils.isNotBlank(persg)) {
            employee.setEmployeeGroupId(configManager.getConfigId("group", persg));
        }

        // 员工子组
        String persk = StringUtils.trimToNull(employeeData.getString("PERSK"));
        if (StringUtils.isNotBlank(persk)) {
            employee.setEmployeeSubgroupId(configManager.getConfigId("subgroup", persk));
        }

        // 入职日期
        employee.setEnterGroupDate(parseDate(StringUtils.trimToNull(employeeData.getString("ZGLRQ"))));

        // 参加工作日期
        employee.setStartWorkingDate(parseDate(StringUtils.trimToNull(employeeData.getString("ZGZRQ"))));

        // 连续工龄计算日期
        employee.setEnterCompanyDate(parseDate(StringUtils.trimToNull(employeeData.getString("ZRZRQ"))));

        // 获聘职称时间
        employee.setHighestProfessionalDate(parseDate(StringUtils.trimToNull(employeeData.getString("ZHRITITLED"))));

        // 最高获聘职称
        String zhrititlel = StringUtils.trimToNull(employeeData.getString("ZHRITITLEL"));
        if (StringUtils.isNotBlank(zhrititlel)) {
            employee.setHighestProfessionalTitleId(configManager.getConfigId("professionalTitle", zhrititlel));
        }

        // 技能等级
        String zhrzlevel = StringUtils.trimToNull(employeeData.getString("ZHRZLEVEL"));
        if (StringUtils.isNotBlank(zhrzlevel)) {
            employee.setSkillLevelId(configManager.getConfigId("skillLevel", zhrzlevel));
        }

        // 最高学历
        String zhrjyxl = StringUtils.trimToNull(employeeData.getString("ZHRJYXL"));
        if (StringUtils.isNotBlank(zhrjyxl)) {
            employee.setHighestEducationId(configManager.getConfigId("education", zhrjyxl));
        }

        // 最高学位
        String zhrjyxwf = StringUtils.trimToNull(employeeData.getString("ZHRJYXWF"));
        if (StringUtils.isNotBlank(zhrjyxwf)) {
            employee.setHighestDegreeId(configManager.getConfigId("degree", zhrjyxwf));
        }

        // 最高毕业院校
        String zhrjybyyx = StringUtils.trimToNull(employeeData.getString("ZHRJYBYYX"));
        if (StringUtils.isNotBlank(zhrjybyyx)) {
            employee.setHighestDegreeSchoolId(configManager.getConfigId("school", zhrjybyyx));
        }

        // 最高学位专业
        String zhrjyzyf = StringUtils.trimToNull(employeeData.getString("ZHRJYZYF"));
        if (StringUtils.isNotBlank(zhrjyzyf)) {
            employee.setHighestDegreeMajorId(configManager.getConfigId("major", zhrjyzyf));
        }

        // 第一学历
        String zhrjyxlF = StringUtils.trimToNull(employeeData.getString("ZHRJYXL_F"));
        if (StringUtils.isNotBlank(zhrjyxlF)) {
            employee.setFirstEducationId(configManager.getConfigId("education", zhrjyxlF));
        }

        // 第一学历毕业院校
        String zhrjybyyxF = StringUtils.trimToNull(employeeData.getString("ZHRJYBYYX_F"));
        if (StringUtils.isNotBlank(zhrjybyyxF)) {
            employee.setFirstEducationSchoolId(configManager.getConfigId("school", zhrjybyyxF));
        }

        // 第一学历专业
        String zhrjyzyfF = StringUtils.trimToNull(employeeData.getString("ZHRJYZYF_F"));
        if (StringUtils.isNotBlank(zhrjyzyfF)) {
            employee.setFirstEducationMajorId(configManager.getConfigId("major", zhrjyzyfF));
        }

        // 学习形式
        String zhrjyxs = StringUtils.trimToNull(employeeData.getString("ZHRJYXS"));
        if (StringUtils.isNotBlank(zhrjyxs)) {
            employee.setLearningFormId(configManager.getConfigId("learningForm", zhrjyxs));
        }

        // 是否在职
        String flag1 = StringUtils.trimToNull(employeeData.getString("FLAG1"));
        if (StringUtils.isNotBlank(flag1)) {
            employee.setStatus(Integer.parseInt(flag1));
        }

        return employee;
    }

    private Date parseDate(String dateString) {
        if (StringUtils.isBlank(dateString)) {
            return null;
        }
        try {
            return new SimpleDateFormat("yyyyMMdd").parse(dateString);
        } catch (ParseException e) {
            log.error("日期解析错误: {}", dateString, e);
            return null;
        }
    }

    private void preCreateConfig(JSONObject employeeData) {
        // 民族
        String zminzu = StringUtils.trimToNull(employeeData.getString("ZMINZU"));
        if (StringUtils.isNotBlank(zminzu)) {
            configManager.createConfig("ethnicity", zminzu);
        }

        // 籍贯
        String zhrhometown = StringUtils.trimToNull(employeeData.getString("ZHRHOMETOWN"));
        if (StringUtils.isNotBlank(zhrhometown)) {
            configManager.createConfig("nativePlace", zhrhometown);
        }

        // 产业集团（二级）
//        String orgtxGroup = StringUtils.trimToNull(employeeData.getString("ORGTX_GROUP"));
//        if (StringUtils.isNotBlank(orgtxGroup)) {
//            configManager.createConfig("industrialGroup", orgtxGroup);
//        }

        // 一级部门
        String orgtx1 = StringUtils.trimToNull(employeeData.getString("ORGTX1"));
        if (StringUtils.isNotBlank(orgtx1)) {
            configManager.createConfig("department", orgtx1);
        }

        // 二级部门
        String orgtx2 = StringUtils.trimToNull(employeeData.getString("ORGTX2"));
        if (StringUtils.isNotBlank(orgtx2)) {
            configManager.createConfig("department", orgtx2);
        }

        // 三级部门
        String orgtx3 = StringUtils.trimToNull(employeeData.getString("ORGTX3"));
        if (StringUtils.isNotBlank(orgtx3)) {
            configManager.createConfig("department", orgtx3);
        }

        // 一级岗位目录
        String zyjgwml = StringUtils.trimToNull(employeeData.getString("ZYJGWML"));
        // 一级岗位目录文本
        String zyjgwwb = StringUtils.trimToNull(employeeData.getString("ZYJGWWB"));
        if (StringUtils.isNotBlank(zyjgwwb)) {
            configManager.createConfig("primaryLevelJob", zyjgwwb);
        }

        // 二级岗位目录
        String zejgwml = StringUtils.trimToNull(employeeData.getString("ZEJGWML"));
        // 二级岗位目录文本
        String zejgwwb = StringUtils.trimToNull(employeeData.getString("ZEJGWWB"));
        if (StringUtils.isNotBlank(zejgwml) && StringUtils.isNotBlank(zejgwwb)) {
            configManager.createConfig("secondaryLevelJob", zejgwml, zejgwwb);
        }

        // 三级岗位目录
        String zsjgwml = StringUtils.trimToNull(employeeData.getString("ZSJGWML"));
        // 三级岗位目录文本
        String zsjgwwb = StringUtils.trimToNull(employeeData.getString("ZSJGWWB"));
        if (StringUtils.isNotBlank(zsjgwml) && StringUtils.isNotBlank(zsjgwwb)) {
            configManager.createConfig("tertiaryLevelJob", zsjgwml, zsjgwwb);
        }

        // 最高获聘职称
        String zhrititleh = StringUtils.trimToNull(employeeData.getString("ZHRITITLEH"));
        if (StringUtils.isNotBlank(zhrititleh)) {
            configManager.createConfig("professionalTitle", zhrititleh);
        }

        // 最高毕业院校
        String zhrjybyyx = StringUtils.trimToNull(employeeData.getString("ZHRJYBYYX"));
        // 院校标识
        if (StringUtils.isNotBlank(zhrjybyyx)) {
            configManager.createConfig("school", zhrjybyyx);
        }

        // 最高学位专业
        String zhrjyzyf = StringUtils.trimToNull(employeeData.getString("ZHRJYZYF"));
        if (StringUtils.isNotBlank(zhrjyzyf)) {
            configManager.createConfig("major", zhrjyzyf);
        }

        // 第一学历毕业院校
        String zhrjybyyxF = StringUtils.trimToNull(employeeData.getString("ZHRJYBYYX_F"));
        if (StringUtils.isNotBlank(zhrjybyyxF)) {
            configManager.createConfig("school", zhrjybyyx);
        }

        // 第一学历专业
        String zhrjyzyfF = StringUtils.trimToNull(employeeData.getString("ZHRJYZYF_F"));
        if (StringUtils.isNotBlank(zhrjyzyfF)) {
            configManager.createConfig("major", zhrjyzyfF);
        }
    }
}
